<template>
  <div class="zlcj-map-layer-content">
    <div ref="mapAr" id="mapAr"></div>
    <mapDom
      :currentData="currentData"
      @setPoint="setPoint"
      ref="popupContainer"
    ></mapDom>
    <div class="left-video">
      <videoPlay
        :currentData="currentPoint"
        v-if="currentPoint.cameraIndexCode"
      ></videoPlay>
    </div>
  </div>
</template>

<script setup>
import "ol/ol.css";
import {
  ref,
  onMounted,
  defineComponent,
  defineEmits,
  nextTick,
  onUnmounted,
} from "vue";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
import Feature from "ol/Feature";
import { LineString, Point, Polygon } from "ol/geom";
import { Icon, Style, Stroke, Circle, Fill, Text } from "ol/style";
import Overlay from "ol/Overlay.js";
import { Image as ImageLayer } from "ol/layer.js";
import ImageWMS from "ol/source/ImageWMS.js";
import VectorTileSource from "ol/source/VectorTile";
import VectorTileLayer from "ol/layer/VectorTile";
import MVT from "ol/format/MVT";
import { defaults } from "ol/interaction/defaults";
import PointerInteraction from "ol/interaction/Pointer";
import DragPan from "ol/interaction/DragPan";
import mapDom from "../map-component/mapDom.vue";
import emitter from "@/utils/mitt";
import { getMapData } from "@/api/zlcj.js";
import { MinxfunCoulmns } from "./device.js";
const { findSenceType } = MinxfunCoulmns();
import videoPlay from "../map-component/videoplay.vue";
// 视频
import sp from "@/assets/map/sp.png";
import spa from "@/assets/map/spa.png";

// 噪音
import zy from "@/assets/map/zy.png";
import zya from "@/assets/map/zya.png";

// 内涝
import nl from "@/assets/map/nla.png";
import nla from "@/assets/map/nla.png";

// 气象
import qx from "@/assets/map/qx.png";
// import qxa from '@/assets/map/qxa.png';

const route = useRoute();
const mapAr = ref(null);
const animating = ref(false);
let map;
let arrPoint = ref([]);
let polyonArr = ref([]);

// 添加点位
let highLayer = null;
let allhighFectures = [];
let gdList = ref([]);
let currentHigh = ref({});
// 获取点位设备
const getData = async () => {
  try {
    let { data } = await getMapData({
      sceneCode: await findSenceType(route.params.id),
    });
    gdList.value = data.list;
  } catch (e) {
    console.error(e);
  }
};
const getImg = (val) => {
  console.log("val", val);
  let type = null;
  if (val.length > 0) {
    console.log("val[0]", val[0]);
    type = val[0].device_type;
  }
  console.log("type", type);

  // 这里通过判断devices的长度来判断展示的具体图标是啥：联调的时候再写
  switch (type) {
    case "3001":
      return nl;
    case "fh":
      return sp;
    case "cw":
      return sp;
    case "lj":
      return sp;
    case "shj":
      return sp;
    case "2010":
      return qx;
    case "2020":
      return qx;
    case "2050":
      return qx;
    case "2030":
      return qx;
    case "cg":
      return sp;
    case "2040":
      return zy;
    default:
      return sp;
  }
};

const getImgA = (val) => {
  console.log("val", val);
  let type = null;
  if (val.length > 0) {
    console.log("val[0]", val[0]);
    type = val[0].device_type;
  }
  console.log("type", type);

  // 这里通过判断devices的长度来判断展示的具体图标是啥：联调的时候再写
  switch (type) {
    case "3001":
      return nla;
    case "fh":
      return spa;
    case "cw":
      return spa;
    case "lj":
      return spa;
    case "shj":
      return spa;
    case "2010":
      return qxa;
    case "2020":
      return qxa;
    case "2050":
      return qxa;
    case "2030":
      return qxa;
    case "cg":
      return spa;
    case "2040":
      return zya;
    default:
      return spa;
  }
};
// 添加点位设备
const addPointLayer = async () => {
  await getData();
  if (!map) return;
  let brr = [];
  let arr = gdList.value;
  // 1、初始化点位的图层
  highLayer = new VectorLayer({
    source: new VectorSource(),
  });
  allhighFectures = [];
  for (let i = 0; i < arr.length; i++) {
    // 2、创建点位的feature
    let feature = new Feature({
      geometry: new Point([arr[i].lng, arr[i].lat]),
      attrs: {
        // type: "point",
        // name: "点位1",
        // url: "http://10.198.12.12.m3u8",
        ...arr[i],
      },
      draggable: false,
    });

    feature.setStyle(
      new Style({
        image: new Icon({
          src: getImg(arr[i].devices),
          width: 40,
          height: 48,
        }),
        // text: new Text({
        //   text: arr[i].deviceCount, // 从要素属性中获取文本
        //   font: "12px Arial", // 字体样式
        //   fill: new Fill({ color: "#fff" }), // 文本填充颜色
        //   offsetX: 0, // 水平偏移
        //   offsetY: 1, // 垂直偏移
        //   textAlign: "center", // 文本对齐方式
        //   textBaseline: "center", // 文本基线
        // }),
      })
    );
    allhighFectures.push(feature);
  }
  console.log("allhighFectures", allhighFectures);
  // 3 、 将feature添加到layer中
  highLayer.getSource().addFeatures(allhighFectures);

  // 4、将feauture添加到layser

  map.addLayer(highLayer);
  highLayer.setZIndex(9);
};

const changeHighBg = (data) => {
  for (let i = 0; i < allhighFectures.length; i++) {
    let attrs = allhighFectures[i].get("attrs");
    for (let j = 0; j < attrs.devices.length; j++) {
      if (data.deviceId === attrs.devices[j].device_id) {
        allhighFectures[i].setStyle(
          new Style({
            image: new Icon({
              src: getImgA(attrs.devices),
              width: 40,
              height: 48,
            }),
          })
        );
        break;
      } else {
        allhighFectures[i].setStyle(
          new Style({
            image: new Icon({
              src: getImg(attrs.devices),
              width: 40,
              height: 48,
            }),
          })
        );
      }
    }
  }
};

// 展示弹框详情
const currentData = ref({});
const popupContainer = ref();
const overlay = ref(null);
const showDetailPop = (data) => {
  try {
    // 创建叠加层
    // console.log(popupContainer.value);
    const dom = document.getElementById("mapdom");
    overlay.value = new Overlay({
      // element: popupContainer.value,
      element: dom,
      autoPan: true,
      autoPanAnimation: {
        duration: 250,
      },
    });
    overlay.value.setPosition([data.lng, data.lat]);
    map.addOverlay(overlay.value);
  } catch (e) {
    console.error(e);
  }
};

const setVideo = (row) => {
  if (currentData.value.device_id == row.deviceId) return;
  if (overlay.value) {
    currentData.value = {};
    emitter.emit("closeVideo");
    overlay.value.setPosition(undefined);
  }
  let view = map.getView();
  if (row.lng && row.lat) {
    view.setCenter([row.lng, row.lat]);
  }

  currentData.value = {
    ...row,
    device_id: row.deviceId,
    cameraIndexCode: row.cameraIndexCode,
  };
  nextTick(() => {
    showDetailPop(currentData.value);
  });
};

let currentPoint = ref({});
const setPoint = (point) => {
  currentPoint.value = point;

  changeHighBg(point);
};

onMounted(async () => {
  map = new Map({
    layers: [
      new ImageLayer({
        source: new ImageWMS({
          url: "/geoserver/bcd/wms",
          params: { LAYERS: "bcd", VERSION: "1.1.0" },
          ratio: 1,
          serverType: "geoserver",
        }),
      }),
    ],
    target: mapAr.value,
    view: new View({
      center: [117.74256851451989, 39.00380206757584],
      projection: "EPSG:4326",
      minZoom: 4,
      zoom: 11.7,
    }),
    interactions: defaults({
      doubleClickZoom: false,
    }),
    controls: [],
  });
  // 监听地图的postrender事件
  map.once("postrender", (event) => {
    addPointLayer();
  });

  // 监听视图变化（包括移动和缩放）
  map.on("moveend", function () {
    if (overlay.value && currentData.value.type) {
      emitter.emit("screenChange");
    }
  });

  // 地图注册点击事件
  map.on("click", (event) => {
    let point = event.coordinate;
    console.log(point);
    // 获取点击的要素
    const clickedFeature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
      return feature;
    });
    if (overlay.value) {
      currentData.value = {};
      emitter.emit("closeVideo");
      overlay.value.setPosition(undefined);
    }
    if (clickedFeature && clickedFeature.get("attrs")) {
      let data = clickedFeature.get("attrs");
      console.log("currentData", data);

      if (data && data.id) {
        currentData.value = data;
        showDetailPop(data);
      }
    }
  });

  emitter.on("playMapVideo", setVideo);
});
onUnmounted(() => {
  emitter.off("playMapVideo", setVideo);
});

const getView = () => {
  // localStorage.setItem("polython", JSON.stringify(polyonArr.value));
  // return;
  let view = map.getView();
  let center = view.getCenter();
  console.log(center);
  console.log(view);
  center[0] = center[0] - 1;
  center[1] = center[1] - 1;
  view.setCenter(center);
  map.render();

  view.animate({
    center: [114.28, 34.54],
    zoom: 7,
    duration: 1000,
  });

  // 获取图层方法:等等
  // map.getLayers().item[1].getSource().on('click')
};
</script>

<style lang="scss" scoped>
.zlcj-map-layer-content {
  width: 100%;
  height: 100%;
  #mapAr {
    width: 100%;
    height: 100%;
    overflow: hidden;
    opacity: 1;
  }
  .left-video {
    position: absolute;
    left: 20px;
    bottom: 10px;
    width: 450px;
    height: 300px;
    // border: 1px solid red;
    z-index: 999;
  }
}
</style>
